import React, { useState, useEffect } from 'react'
import { 
  Row, 
  Col, 
  Card, 
  Table, 
  Button, 
  Tag, 
  Space, 
  Input, 
  Select, 
  DatePicker,
  Modal,
  Form,
  message 
} from 'antd'
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  SearchOutlined,
  EyeOutlined,
  PlayCircleOutlined,
  PictureOutlined,
  FileTextOutlined
} from '@ant-design/icons'
import { mockApi, ContentItem } from '@/services/mockData'
import dayjs from 'dayjs'

const { Option } = Select
const { RangePicker } = DatePicker

const ContentCenter: React.FC = () => {
  const [contentData, setContentData] = useState<ContentItem[]>([])
  const [loading, setLoading] = useState(true)
  const [searchParams, setSearchParams] = useState({
    keyword: '',
    type: '',
    status: '',
    dateRange: [] as any[]
  })
  const [modalVisible, setModalVisible] = useState(false)
  const [editingContent, setEditingContent] = useState<ContentItem | null>(null)
  const [form] = Form.useForm()

  useEffect(() => {
    fetchContentData()
  }, [])

  const fetchContentData = async () => {
    setLoading(true)
    try {
      // 尝试从localStorage获取数据
      const storedData = localStorage.getItem('contentData')
      if (storedData) {
        setContentData(JSON.parse(storedData))
      } else {
        // 如果没有存储的数据，从mockApi获取
        const data = await mockApi.getContentList()
        setContentData(data)
        // 保存到localStorage
        localStorage.setItem('contentData', JSON.stringify(data))
      }
    } catch (error) {
      message.error('获取内容数据失败')
    } finally {
      setLoading(false)
    }
  }

  const handleSearch = () => {
    // 模拟搜索逻辑
    fetchContentData()
  }

  const handleCreate = () => {
    setEditingContent(null)
    setModalVisible(true)
    form.resetFields()
  }

  const handleEdit = (record: ContentItem) => {
    setEditingContent(record)
    setModalVisible(true)
    form.setFieldsValue({
      ...record,
      createTime: record.createTime ? dayjs(record.createTime) : undefined
    })
  }

  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条内容吗？',
      onOk: () => {
        try {
          // 从localStorage获取数据
          const storedData = localStorage.getItem('contentData')
          if (storedData) {
            const data = JSON.parse(storedData)
            // 过滤掉要删除的数据
            const filteredData = data.filter((item: ContentItem) => item.id !== id)
            // 保存到localStorage
            localStorage.setItem('contentData', JSON.stringify(filteredData))
            // 更新状态
            setContentData(filteredData)
          }
          message.success('删除成功')
        } catch (error) {
          message.error('删除失败')
        }
      }
    })
  }

  const handleSubmit = async (values: any) => {
    try {
      // 从localStorage获取数据
      const storedData = localStorage.getItem('contentData')
      let data: ContentItem[] = storedData ? JSON.parse(storedData) : []
      
      if (editingContent) {
        // 更新现有内容
        data = data.map(item => 
          item.id === editingContent.id 
            ? { ...item, ...values, createTime: values.createTime?.format('YYYY-MM-DD HH:mm') || item.createTime }
            : item
        )
        message.success('更新成功')
      } else {
        // 创建新内容
        const newContent: ContentItem = {
          ...values,
          id: `content_${Date.now()}`,
          createTime: values.createTime?.format('YYYY-MM-DD HH:mm') || dayjs().format('YYYY-MM-DD HH:mm'),
          views: 0
        }
        data.unshift(newContent)
        message.success('创建成功')
      }
      
      // 保存到localStorage
      localStorage.setItem('contentData', JSON.stringify(data))
      // 更新状态
      setContentData(data)
      
      setModalVisible(false)
    } catch (error) {
      message.error('操作失败')
    }
  }

  const getTypeIcon = (type: string) => {
    const icons = {
      article: <FileTextOutlined style={{ color: '#1890ff' }} />,
      video: <PlayCircleOutlined style={{ color: '#f5222d' }} />,
      audio: <PlayCircleOutlined style={{ color: '#52c41a' }} />,
      image: <PictureOutlined style={{ color: '#faad14' }} />
    }
    return icons[type as keyof typeof icons] || <FileTextOutlined />
  }

  const columns = [
    {
      title: '内容标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: ContentItem) => (
        <Space>
          {getTypeIcon(record.type)}
          <span style={{ fontWeight: 500 }}>{text}</span>
        </Space>
      )
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const typeMap = {
          article: { color: 'blue', text: '文章' },
          video: { color: 'red', text: '视频' },
          audio: { color: 'orange', text: '音频' },
          image: { color: 'green', text: '图片' }
        }
        const config = typeMap[type as keyof typeof typeMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          published: { color: 'success', text: '已发布' },
          draft: { color: 'default', text: '草稿' },
          reviewing: { color: 'processing', text: '审核中' }
        }
        const config = statusMap[status as keyof typeof statusMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '浏览量',
      dataIndex: 'views',
      key: 'views',
      render: (views: number) => (
        <span style={{ color: '#1890ff', fontWeight: 500 }}>
          {views.toLocaleString()}
        </span>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (record: ContentItem) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            size="small"
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            size="small"
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  const handleView = (record: ContentItem) => {
    // 查看内容详情
    Modal.info({
      title: record.title,
      content: (
        <div>
          <p>类型: {record.type}</p>
          <p>作者: {record.author}</p>
          <p>创建时间: {dayjs(record.createTime).format('YYYY-MM-DD HH:mm')}</p>
          <p>状态: {record.status}</p>
          <p>浏览量: {record.views}</p>
        </div>
      ),
      onOk: () => {
        try {
          // 增加浏览量
          const updatedData = contentData.map(item => 
            item.id === record.id ? { ...item, views: item.views + 1 } : item
          )
          setContentData(updatedData)
          // 更新localStorage
          localStorage.setItem('contentData', JSON.stringify(updatedData))
        } catch (error) {
          message.error('更新浏览量失败')
        }
      }
    })
  }

  return (
    <div>
      <div className="page-title">
        <EditOutlined />
        内容生产中心
      </div>

      {/* 搜索区域 */}
      <Card style={{ marginBottom: 16 }} className="custom-card">
        <Row gutter={16}>
          <Col xs={24} sm={8}>
            <Input
              placeholder="搜索内容标题"
              value={searchParams.keyword}
              onChange={(e) => setSearchParams({...searchParams, keyword: e.target.value})}
              prefix={<SearchOutlined />}
            />
          </Col>
          <Col xs={24} sm={4}>
            <Select
              placeholder="内容类型"
              value={searchParams.type}
              onChange={(value) => setSearchParams({...searchParams, type: value})}
              style={{ width: '100%' }}
              allowClear
            >
              <Option value="article">文章</Option>
              <Option value="video">视频</Option>
              <Option value="audio">音频</Option>
              <Option value="image">图片</Option>
            </Select>
          </Col>
          <Col xs={24} sm={4}>
            <Select
              placeholder="发布状态"
              value={searchParams.status}
              onChange={(value) => setSearchParams({...searchParams, status: value})}
              style={{ width: '100%' }}
              allowClear
            >
              <Option value="published">已发布</Option>
              <Option value="draft">草稿</Option>
              <Option value="reviewing">审核中</Option>
            </Select>
          </Col>
          <Col xs={24} sm={6}>
            <RangePicker
              style={{ width: '100%' }}
              onChange={(dates) => setSearchParams({...searchParams, dateRange: dates as any[]})}
            />
          </Col>
          <Col xs={24} sm={2}>
            <Button type="primary" onClick={handleSearch} style={{ width: '100%' }}>
              搜索
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 内容列表 */}
      <Card 
        title="内容列表"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新建内容
          </Button>
        }
        className="custom-card"
      >
        <Table
          columns={columns}
          dataSource={contentData}
          loading={loading}
          rowKey="id"
          pagination={{
            total: contentData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条内容`
          }}
        />
      </Card>

      {/* 新建/编辑模态框 */}
      <Modal
        title={editingContent ? '编辑内容' : '新建内容'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="title"
            label="内容标题"
            rules={[{ required: true, message: '请输入内容标题' }]}
          >
            <Input placeholder="请输入内容标题" />
          </Form.Item>

          <Form.Item
            name="type"
            label="内容类型"
            rules={[{ required: true, message: '请选择内容类型' }]}
          >
            <Select placeholder="请选择内容类型">
              <Option value="article">文章</Option>
              <Option value="video">视频</Option>
              <Option value="audio">音频</Option>
              <Option value="image">图片</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="发布状态"
            rules={[{ required: true, message: '请选择发布状态' }]}
          >
            <Select placeholder="请选择发布状态">
              <Option value="draft">草稿</Option>
              <Option value="reviewing">审核中</Option>
              <Option value="published">已发布</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="author"
            label="作者"
            rules={[{ required: true, message: '请输入作者' }]}
          >
            <Input placeholder="请输入作者" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingContent ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default ContentCenter